<?php
class MHtmlTable {
    private $_columns = array();
    private $_data;
    public $featured = false;

    public function __construct($data = array(), $columnsToHide = array()) {
        $this->_data = $data;
        if (!empty ($this->_data)){
            $row = $this->_data[0];
            if ($row instanceof MModel){
                foreach ($row->attributes() as $key=>$value){
                    if (!in_array ($key, $columnsToHide)) {
                        $column = new MHtmlDataColumn(get_class($row), $key, $this);
                        array_push($this->_columns, $column);
                    }
                }
            } else {
                foreach ($row as $col){
                    $column = new MHtmlColumn($this);
                    array_push($this->_columns, $column);
                }
            }
        }
    }
    
    public function addColumn($column){
        array_push($this->_columns, $column);
    }
    
    public function render(){
        MPackage::import('mandrill-table-css');
        if ($this->featured){
            MPackage::import('jquery-datatables');
        }
        $tableContent = '';
        if (!empty($this->_columns)){
            $rowContent = '';
            foreach ($this->_columns as $column){
                $rowContent .= $column->renderHeader();
            }
            $tableContent .= MHtml::tag('thead', array(), MHtml::tag('tr', array('class'=>'ml-row-header'), $rowContent));
            $n = count($this->_data);
            $bodyContent = '';
            for ($row = 0; $row < $n; $row++){
                $rowContent = '';
                foreach ($this->_columns as $column){
                    $rowContent .= $column->renderBody($row);
                }
                $bodyContent .= MHtml::tag('tr', array('class'=>'ml-row-header'), $rowContent);
            }
            $tableContent .= MHtml::tag('tbody', array(), $bodyContent);
        }
        return MHtml::tag('table', array('class'=>'ml-table'), $tableContent);
    }
    
    public function getRow($rowIndex){
        return $this->_data[$rowIndex];
    }
    
    public function getData() {
        return $this->_data;
    }

    public function setData($_data) {
        $this->_data = $_data;
    }

    public function getLength(){
        return count($this->_data);
    }
   
    public function __toString() {
        return $this->render();
    }
}
?>
